﻿using System;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Xml.Serialization;
using System.Xml;
using System.Net;
using System.IO;
using HPCloud.Common.Properties;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using System.Xml.Serialization;

namespace HPCloud.Common.DataAccess
{
    public class Repository2 : HttpClient
    {
        private string _lastResponseContent;
        private HttpResponseMessage _lastResponseMessage;
        private NameValueCollection _commonHttpRequestHeaders;
        private Settings _settings;
        //private Context _context;

        #region Ctors
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        //==================================================================================================================
        public Repository2(Settings settings, NameValueCollection commonHttpRequestHeaders)
        {
            _settings                 = settings;
            _commonHttpRequestHeaders = commonHttpRequestHeaders;
                        
            //string storageToken = commonHttpRequestHeaders["X-Storage-Token"];
            //string authToken = commonHttpRequestHeaders["X-Auth-Token"];
            //_commonHttpRequestHeaders =  HttpRequestHeaders
           
            //_commonHttpRequestHeaders.Add("X-Storage-Token", storageToken);
            //_commonHttpRequestHeaders.Add("X-Auth-Token", authToken);
        }
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        //==================================================================================================================
        public Repository2(Settings settings)
        {
            _settings = settings;
        }
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        //==================================================================================================================
        public Repository2()
        {
            _settings = Settings.Default;
        }
        #endregion
        #region Properties
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        //==================================================================================================================
        protected NameValueCollection CommonHttpRequestHeaders
        {
            get { return _commonHttpRequestHeaders; }
            set { _commonHttpRequestHeaders = value; }
        }
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        //==================================================================================================================
        public HttpResponseMessage LastResponseMessage
        {
            get { return _lastResponseMessage; }
        }
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        //==================================================================================================================
        protected Settings Settings
        {
            get
            {
                return _settings;
            }
        }
        #endregion
        #region Methods
        //================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        //================================================================================
        protected bool IsMocked
        {
            get
            {
                return this.Settings.IsMocked;
            }
        }
        //================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        //================================================================================
        protected NameValueCollection BuildCommonHttpRequestHeaders()
        {
            //HttpRequestHeaders headers = new HttpRequestHeaders();

            //foreach (IEnumerable<string> header in this.CommonHttpRequestHeaders)
            //{
            //    headers.Add(header.Key, header.Value);
            //}

           // return headers;
            return null;
        }

        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <param name="resourcePath"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        //==================================================================================================================
        //protected T InvokeEndpoint<T>(HttpMethod method, string absoluteURI, NameValueCollection queryString) where T : class
        //{
        //    return this.InvokeEndpoint<T>(method, absoluteURI, queryString, null);
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        //==================================================================================================================
        protected bool IsStatusNormal(HttpStatusCode status)
        {
            if (status != HttpStatusCode.OK &&
                status != HttpStatusCode.Created &&
                status != HttpStatusCode.NoContent &&
                status != HttpStatusCode.Accepted
                )
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        //==================================================================================================================
        protected HttpClient CreateHttpClient()
        {
            int timeout = Settings.HttpTimeoutInterval;
            HttpClient client = new HttpClient();
            //client.TransportSettings.ReadWriteTimeout = new TimeSpan(0, 0, 0, timeout);
            //client.TransportSettings.ConnectionTimeout = new TimeSpan(0, 0, 0, timeout);

            HttpRequestMessage  re = new HttpRequestMessage();
            re.RequestUri = null;


            return client;
        }
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="uri=Offset"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        //==================================================================================================================
        ////////protected string GetStringResponse(HttpMethod method, string absoluteURI, NameValueCollection queryString, HttpRequestHeaders headers)
        ////////{
        ////////    Uri uri = new Uri(absoluteURI);

        ////////    using (HttpClient client = this.CreateHttpClient())
        ////////    {
        ////////        if (queryString != null)
        ////////        {
        ////////          //  uri = queryString.MakeQueryString(uri);
        ////////        }

        ////////       // client.TransportSettings.AllowWriteStreamBuffering = true;

        ////////        if (headers != null)
        ////////        {
        ////////            //client.DefaultHeaders = headers;
        ////////        }

        ////////        using (HttpResponseMessage msg = client.Send(method, uri))
        ////////        {
        ////////            // This allows multiple reads from the same stream..

        ////////            msg.Content.LoadIntoBuffer();

        ////////            // Anything other than an Http status of OK or CREATED is considered an exception..

        ////////            if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        ////////            {
        ////////                using (HttpResponseMessage newMsg = client.Send(method, uri))
        ////////                {
        ////////                    // This allows multiple reads from the same stream..

        ////////                    newMsg.Content.LoadIntoBuffer();
        ////////                    return newMsg.Content.ReadAsString();
        ////////                }
        ////////            }

        ////////            if (!this.IsStatusNormal(msg.StatusCode))
        ////////            {
        ////////                //throw ExceptionFactory.CreateException(msg);
        ////////            }
        ////////            else
        ////////            {
        ////////               // msg.EnsureStatusIsSuccessful();

        ////////                // Deserialize the content back out in the format expected by the client. (of T)

        ////////                return msg.Content.ReadAsString();
        ////////            }
        ////////        }
        ////////    }
        ////////}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="uri=Offset"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        //==================================================================================================================
        //protected T InvokeEndpoint<T>(HttpMethod method, string absoluteURI, NameValueCollection queryString, HttpRequestHeaders headers) where T : class
        //{
        //    Uri uri = new Uri(absoluteURI);

        //    using (HttpClient client = this.CreateHttpClient())
        //    {
        //        if (queryString != null)
        //        {
        //           // uri = queryString.MakeQueryString(uri);
        //        }

        //      //  client.TransportSettings.AllowWriteStreamBuffering = true;


        //        if (headers != null)
        //        {
        //           // client.DefaultHeaders = headers;
        //        }

        //        using (HttpResponseMessage msg = client.Send(method, uri))
        //        {
        //            // This allows multiple reads from the same stream..

        //            msg.Content.LoadIntoBuffer();

        //            // Anything other than an Http status of OK or CREATED is considered an exception..

        //            if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        //            {
        //                using (HttpResponseMessage newMsg = client.Send(method, uri))
        //                {
        //                    // This allows multiple reads from the same stream..

        //                    newMsg.Content.LoadIntoBuffer();
        //                    return newMsg.Content.ReadAsXmlSerializable<T>();
        //                }

        //            }

        //            if (!this.IsStatusNormal(msg.StatusCode))
        //            {
        //                throw ExceptionFactory.CreateException(msg);
        //            }
        //            else
        //            {
        //                msg.EnsureStatusIsSuccessful();

        //                // Deserialize the content back out in the format expected by the client. (of T)

        //                try
        //                {
        //                    return msg.Content.ReadAsXmlSerializable<T>();
        //                }
        //                catch (FileNotFoundException)
        //                {
        //                    return null;
        //                }
        //            }
        //        }
        //    }
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="method"></param>
        /// <param name="resourcePath"></param>
        /// <param name="queryString"></param>
        //==================================================================================================================
        //protected void InvokeEndpoint(HttpMethod method, string absoluteURI, HttpQueryString queryString)
        //{
        //    this.InvokeEndpoint(method, absoluteURI, queryString, null);
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="method"></param>
        /// <param name="resourcePath"></param>
        /// <param name="headers"></param>
        /// <param name="content"></param>
        //==================================================================================================================
        //protected void InvokeEndpoint(HttpMethod method, string absoluteURI, HttpRequestHeaders headers, HttpContent content, HttpQueryString queryString)
        //{
        //    Uri uri = new Uri(absoluteURI);

        //    using (HttpClient client = this.CreateHttpClient())
        //    {
        //        if (queryString != null)
        //        {
        //            uri = queryString.MakeQueryString(uri);
        //        }

        //        //client.TransportSettings.AllowWriteStreamBuffering = true;
                

        //        if (headers != null)
        //        {
        //            //client.DefaultHeaders = headers;
        //        }

        //        HttpResponseMessage msg = client.Send(method, uri, headers, content);

        //        if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        //        {
        //            HttpClient client2 = this.CreateHttpClient();
        //            HttpResponseMessage newMsg = client2.Send(method, uri, headers, content);
        //        }

        //        if (!this.IsStatusNormal(msg.StatusCode))
        //        {
        //            //throw ExceptionFactory.CreateException(msg);
        //        }
        //        else
        //        {
        //            //msg.EnsureStatusIsSuccessful();
        //        }
        //        client.Dispose();
        //        msg.Dispose();
        //    }
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="method"></param>
        /// <param name="resourcePath"></param>
        /// <param name="headers"></param>
        /// <param name="content"></param>
        //==================================================================================================================
        //protected void InvokeEndpoint(HttpMethod method, string absoluteURI, HttpRequestHeaders headers, HttpContent content)
        //{
        //    Uri uri = new Uri(absoluteURI);

        //    using (HttpClient client = this.CreateHttpClient())
        //    {
        //      //  HttpResponseMessage msg = client.Send(method, uri, headers, content);

        //        if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        //        {
        //           // HttpResponseMessage newMsg = client.Send(method, uri, headers, content);
        //        }

        //        if (!this.IsStatusNormal(msg.StatusCode))
        //        {
        //           // throw ExceptionFactory.CreateException(msg);
        //        }
        //        else
        //        {
        //           // msg.EnsureStatusIsSuccessful();
        //        }
        //        client.Dispose();
        //        msg.Dispose();
        //    }
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resourcePath"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        //==================================================================================================================
        //protected void InvokeEndpoint(HttpMethod method, string absoluteURI, NameValueCollection queryString, HttpRequestHeaders headers)
        //{
        //    Uri uri = new Uri(absoluteURI);
        //    HttpRequestMessage msg = new HttpRequestMessage(method, )

        //    using (HttpClient client = this.CreateHttpClient())
        //    {
        //        //if (queryString != null)
        //        //{
        //        //    uri = queryString.MakeQueryString(uri);
        //        //}
        //        if (headers != null)
        //        {
        //           // client.DefaultHeaders = headers;
        //        }

        //      //  HttpResponseMessage msg = client.Send(method, uri);

        //        if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        //        {
        //          //  HttpResponseMessage newMsg = client.Send(method, uri);
        //        }


        //        if (!this.IsStatusNormal(msg.StatusCode))
        //        {
        //           // throw ExceptionFactory.CreateException(msg);
        //        }
        //        else
        //        {
        //           // msg.EnsureStatusIsSuccessful();
        //        }

        //        client.Dispose();
        //        msg.Dispose();
        //    }
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <param name="resourcePath"></param>
        /// <returns></returns>
        //==================================================================================================================
        //protected T InvokeEndpoint<T>(HttpMethod method, string absoluteURI) where T : class
        //{
        //    return this.InvokeEndpoint<T>(null, method, absoluteURI);
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <param name="absoluteURI"></param>
        /// <param name="queryString"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        //==================================================================================================================
        //public static T ListObjects<T>(HttpMethod method, string absoluteURI, NameValueCollection queryString, HttpRequestHeaders headers) where T : class
        //{
        //    Uri uri = new Uri(absoluteURI);
        //    int timeout = Settings.Default.HttpTimeoutInterval;
        //    HttpClient client = new HttpClient();
        //    //client.TransportSettings.ReadWriteTimeout = new TimeSpan(0, 0, 0, timeout);
        //    //client.TransportSettings.ConnectionTimeout = new TimeSpan(0, 0, 0, timeout);

        //    using (client)
        //    {
        //        if (queryString != null)
        //        {
        //          //  uri = queryString.MakeQueryString(uri);
        //        }

        //     //   client.TransportSettings.AllowWriteStreamBuffering = true;

        //        if (headers != null)
        //        {
        //           // client.DefaultHeaders = headers;
        //        }

        //        using (HttpResponseMessage msg = client.Send(method, uri))
        //        {

        //            if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        //            {
        //                using (HttpResponseMessage newMsg = client.Send(method, uri))
        //                {
        //                    // This allows multiple reads from the same stream..

        //                    newMsg.Content.LoadIntoBuffer();
        //                    return newMsg.Content.ReadAs<T>();
        //                }
        //            }

        //            // This allows multiple reads from the same stream..

        //            msg.Content.LoadIntoBuffer();

        //            // Anything other than an Http status of OK or CREATED is considered an exception..

        //          //  msg.EnsureStatusIsSuccessful();

        //            // Deserialize the content back out in the format expected by the client. (of T)

        //            return msg.Content.ReadAs<T>();
        //        }
        //    }
        //}
        //==================================================================================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resourcePath"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        //==================================================================================================================
        //protected T InvokeEndpoint<T>(HttpRequestHeaders headers, HttpMethod method, string absoluteURI) where T : class
        //{
        //    Uri uri = new Uri(absoluteURI);

        //    using (HttpClient client = this.CreateHttpClient())
        //    {
        //        if (headers != null)
        //        {
        //            client.DefaultHeaders = headers;
        //        }

        //        HttpResponseMessage msg = client.Send(method, uri);

        //        if (msg.StatusCode == HttpStatusCode.MethodNotAllowed)
        //        {
        //            using (HttpResponseMessage newMsg = client.Send(method, uri))
        //            {
        //                // This allows multiple reads from the same stream..

        //                newMsg.Content.LoadIntoBuffer();
        //                return newMsg.Content.ReadAs<T>();
        //            }
        //        }

        //        // This allows multiple reads from the same stream..

        //        msg.Content.LoadIntoBuffer();

        //        if (!this.IsStatusNormal(msg.StatusCode))
        //        {
        //            //throw ExceptionFactory.CreateException(msg);
        //        }
        //        else
        //        {
        //            //msg.EnsureStatusIsSuccessful();
        //            return msg.Content.ReadAs<T>();
        //        }
        //    }
        //}
        #endregion
    }
}


